﻿using System;
using Windows.UI;
using Windows.UI.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media;

// Pour en savoir plus sur le modèle d'élément Contrôle utilisateur, consultez la page http://go.microsoft.com/fwlink/?LinkId=234236

namespace InterfaceXAML.UserControls
{
    public sealed partial class ColorPicker : UserControl
    {
        public string ColorHex { get; set; }
        public int Red { get; set; }
        public int Green { get; set; }
        public int Blue { get; set; }
        public int Alpha { get; set; } 

        public ColorPicker()
        {
            this.InitializeComponent();
            ColorHex = "#000000";
            ExaCode.Document.SetText(TextSetOptions.Unhide, ColorHex);
        }


        private void RedChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            Red = (int)e.NewValue;
            RGBAToHex();
        }

        private void GreenChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            Green = (int)e.NewValue;
            RGBAToHex();
        }

        private void BlueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            Blue = (int)e.NewValue;
            RGBAToHex();
        }

        
        private void RGBAToHex()
        {
            ColorHex = "#" + ((byte)Red).ToString("X2") + ((byte)Green).ToString("X2") + ((byte)Blue).ToString("X2");
            if (preview == null)
                return;

            preview.Fill = App.ConvertToSolidColorBrush(ColorHex);
            ExaCode.Document.SetText(TextSetOptions.Unhide, ColorHex);
        }

        private void DisplayColorPicker(object sender, RoutedEventArgs e)
        {
            popup.IsOpen = !popup.IsOpen;
        }

        private void ExaCode_TextChanged(object sender, RoutedEventArgs e)
        {
            var hexCode = "";
            ExaCode.Document.GetText(TextGetOptions.NoHidden, out hexCode);

            if (hexCode.Length != 7 || hexCode == ColorHex)
                return;

            ColorHex = hexCode;

            var red = ColorHex.Substring(1, 2);
            var green = ColorHex.Substring(3, 2);
            var blue = ColorHex.Substring(5, 2);

            RedSlider.Value = Convert.ToInt32(red,16);
            GreenSlider.Value = Convert.ToInt32(green,16);
            BlueSlider.Value = Convert.ToInt32(blue,16);

            preview.Fill = App.ConvertToSolidColorBrush(ColorHex);
        }

        public void SetCodeColor(string code)
        {
            ExaCode.Document.SetText(TextSetOptions.Unhide, code);
        }
    }
}
